import { PrismaClient } from "@prisma/client";
import { hash } from "bcrypt";
import { subDays } from "date-fns";

const prisma = new PrismaClient();

async function main() {
  const adminEmail = (process.env.SEED_ADMIN_EMAIL ?? "admin@example.com").toLowerCase();
  const adminPassword = process.env.SEED_ADMIN_PASSWORD ?? "Admin123!";
  const adminDisplayName = process.env.SEED_ADMIN_DISPLAY_NAME ?? "System Admin";

  const adminRole = await prisma.role.upsert({
    where: { name: "ADMIN" },
    update: {},
    create: {
      name: "ADMIN",
      description: "System administrator with full access"
    }
  });

  const managerRole = await prisma.role.upsert({
    where: { name: "MANAGER" },
    update: {},
    create: {
      name: "MANAGER",
      description: "Project manager with scheduling permissions"
    }
  });

  await prisma.role.upsert({
    where: { name: "OPERATOR" },
    update: {},
    create: {
      name: "OPERATOR",
      description: "Operator responsible for daily output submissions"
    }
  });

  const passwordHash = await hash(adminPassword, 12);

  const adminUser = await prisma.user.upsert({
    where: { email: adminEmail },
    update: {
      displayName: adminDisplayName,
      passwordHash,
      isActive: true
    },
    create: {
      email: adminEmail,
      displayName: adminDisplayName,
      passwordHash,
      isActive: true
    }
  });

  await prisma.userRole.upsert({
    where: {
      userId_roleId: {
        userId: adminUser.id,
        roleId: adminRole.id
      }
    },
    update: {},
    create: {
      userId: adminUser.id,
      roleId: adminRole.id
    }
  });

  await prisma.userRole.upsert({
    where: {
      userId_roleId: {
        userId: adminUser.id,
        roleId: managerRole.id
      }
    },
    update: {},
    create: {
      userId: adminUser.id,
      roleId: managerRole.id
    }
  });

  const demoProjectName = process.env.SEED_PROJECT_NAME ?? "Demo Project";

  const demoProjectManager = process.env.SEED_PROJECT_MANAGER ?? "Demo Manager";
  const demoProjectTarget = Number(process.env.SEED_PROJECT_TARGET ?? "1800");

  const project = await prisma.project.upsert({
    where: { name: demoProjectName },
    update: {
      description: "Sample project for first-run testing",
      managerName: demoProjectManager,
      monthlyTarget: demoProjectTarget,
      isActive: true
    },
    create: {
      name: demoProjectName,
      description: "Sample project for first-run testing",
      managerName: demoProjectManager,
      monthlyTarget: demoProjectTarget,
      isActive: true
    }
  });

  const today = new Date();

  await prisma.output.createMany({
    data: [
      {
        projectId: project.id,
        reporterId: adminUser.id,
        value: 120,
        date: subDays(today, 1),
        note: "Seeded output for yesterday"
      },
      {
        projectId: project.id,
        reporterId: adminUser.id,
        value: 150,
        date: today,
        note: "Seeded output for today"
      }
    ]
  });

  console.log("✅ Seed completed. Admin login:", adminEmail);
}

main()
  .catch((error) => {
    console.error("❌ Seed failed", error);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
